package app.biz.service.impl;

import app.biz.config.MongoDataSource;
import app.biz.model.EcgRequest;
import app.biz.model.EcgResponse;
import app.biz.service.EcgRemoteService;
import app.biz.service.EcgResultService;
import app.biz.service.LBService;
import app.framework.util.ConcurrentUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.util.concurrent.ListeningExecutorService;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.io.IOException;

/** Created by shadowedge on 2018/11/24. */
@Service
public class EcgRemoteServiceImpl implements EcgRemoteService {
  private static final Logger logger = LoggerFactory.getLogger(EcgRemoteServiceImpl.class);

  @Autowired MongoDataSource mongo;

  @Value("${service.ecgai.url}")
  private String[] egcaiUrl;

  @Autowired
  LBService lbService;
  @Autowired
  EcgResultService resultService;

  /*使用默认名称、默认线程池(10)*/
  static ListeningExecutorService ecgPool = ConcurrentUtil.instance.getService();

  private static String METHOD = "/ins/json";
  private static OkHttpClient client = new OkHttpClient();

  /**
   * 初始化负载均衡器
   * @return */
  @Bean
  public LBService initLB() {
      return lbService.load(egcaiUrl);
  }

  @Override
  public String getResult(EcgRequest ecgRequest) throws IOException {
    RequestBody body;
    body =
        new FormBody.Builder()
            .add("xmldata", ecgRequest.getXmlData())
            .add("fs", ecgRequest.getFs() + "")
            .add("device_id", ecgRequest.getDevice_id() + "")
            .add("leads", ecgRequest.getLeads() + "")
            .build();
    String url = lbService.get();
    Request request = new Request.Builder()
            .url(url + METHOD)
            .header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED.toString())
            .post(body)
            .build();
    Call call = client.newCall(request);
    Response response = call.execute();
      return response.body().string();
  }

  /**
   * 异步获取和保存结果信息
   * @param sid
   * @param ecgRequest
   */
  @Override
  public void getAndSaveResult(long sid, EcgRequest ecgRequest) {
      try {
      ecgPool.submit(
          () -> {
            try {
              String result = getResult(ecgRequest);
                JSONObject ecgResult = EcgResponse.instance.success(sid, result);
                resultService.saveResult(ecgResult);
            } catch (IOException e) {
              logger.error("操作失败！！", e);
            }
          });
      } catch (Exception e) {
          logger.error("操作失败！！", e);
      }
  }
}
